package com.xuecheng.content.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.TeachplanDto;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-30
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    private TeachplanMapper teachplanMapper;

    // 查询课程计划
    @Override
    public ResponseResult treeNodes(Long courseId) {
        // 1.根据课程id查询数据库
        List<TeachplanVo> voList = teachplanMapper.treeNodes(courseId);
        // 2.筛选一级大纲
        TeachplanVo one = null;
        for (TeachplanVo teachplanVo : voList) {
            if (teachplanVo.getGrade() == 1) {
                one = teachplanVo;
                break;
            }
        }
        // 3.筛选二级章节 （parentId = 一级.id ）
        List<TeachplanVo> towList = new ArrayList<>();
        for (TeachplanVo teachplanVo : voList) {
            if (teachplanVo.getParentid().equals(one.getId())) {  // Long 基本数据类型包装类 不要用==
                towList.add(teachplanVo);
            }
        }
        // 将二级关联到一级中
        one.setTeachPlanTreeNodes(towList);
        // 4.筛选三级小节 （parentId = 二级.id ）
        if (CollectionUtil.isNotEmpty(towList)) {
            for (TeachplanVo tow : towList) {
                // 获取二级id
                Long towId = tow.getId();
                // 声明三级list
                List<TeachplanVo> threeList = new ArrayList<>();
                for (TeachplanVo teachplanVo : voList) {
                    if (teachplanVo.getParentid().equals(towId)) {
                        threeList.add(teachplanVo);
                    }
                }
                // 将三级关联到二级
                tow.setTeachPlanTreeNodes(threeList);
            }
        }
        // 5.返回一级大纲
        return ResponseResult.okResult(one);
    }

    // 查询课程计划
    @Override
    public ResponseResult treeNodes2(Long courseId) {
        // 1.根据课程id查询数据库
        List<TeachplanVo> voList = teachplanMapper.treeNodes(courseId);
        // 2.筛选一级大纲
        TeachplanVo one = voList.stream().filter(teachplanVo -> teachplanVo.getGrade() == 1).findFirst().get();
        // 3.筛选二级章节
        List<TeachplanVo> towList = voList.stream().filter(teachplanVo -> teachplanVo.getParentid().equals(one.getId())).collect(Collectors.toList());
        // 将二级关联到一级
        one.setTeachPlanTreeNodes(towList);
        // 4.筛选三级小节
        if (CollectionUtil.isNotEmpty(towList)) {
            for (TeachplanVo tow : towList) {
                // 获取二级id
                Long towId = tow.getId();
                List<TeachplanVo> threeList = voList.stream().filter(teachplanVo -> teachplanVo.getParentid().equals(towId)).collect(Collectors.toList());
                // 将三级关联到二级
                tow.setTeachPlanTreeNodes(threeList);
            }
        }


        // 5.返回一级大纲
        return ResponseResult.okResult(one);
    }


    @Autowired
    private CourseBaseService courseBaseService;

    // 保存或修改课程计划
    @Override
    public ResponseResult saveOrUpdateTeachplan(TeachplanDto dto) {
        // 1.查询课程信息
        CourseBase courseBase = courseBaseService.getById(dto.getCourseId());
        // 2.判断课程状态
        String auditStatus = courseBase.getAuditStatus();
        if (StrUtil.equals(auditStatus, CourseConstants.AUDIT_COMMIT_STATUS) ||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PASTED_STATUS) ||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        // 3. dto -> teachplan
        Teachplan teachplan = BeanHelper.copyProperties(dto, Teachplan.class);
        // 4.二级章节，需要手动指定parentId
        if (teachplan.getGrade()==2) {
            // 查询一级大纲
            LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper<>();
            qw.eq(Teachplan::getCourseId, teachplan.getCourseId());
            qw.eq(Teachplan::getGrade,1 );
            Teachplan teachplanParent = this.getOne(qw);
            teachplan.setParentid(teachplanParent.getId());
        }

        // 5.添加三级小节，对应课程章节数量+1
        if (teachplan.getId() == null && teachplan.getGrade()==3) {
            courseBase.setPlanNum(courseBase.getPlanNum()+1);
            courseBaseService.updateById(courseBase);
        }
        // 6.新增或修改
        this.saveOrUpdate(teachplan);
        // 7.返回成功
        return ResponseResult.okResult();
    }

    // 删除课程计划
    @Override
    public ResponseResult deleteTeachplan(Long id) {
        // 1.查询课程计划
        Teachplan teachplan = this.getById(id);
        // 2.查询课程信息
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        // 3.判断课程信息状态
        String auditStatus = courseBase.getAuditStatus();
        if (StrUtil.equals(auditStatus, CourseConstants.AUDIT_COMMIT_STATUS) ||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PASTED_STATUS) ||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        // 4.判断计划级别
        if (teachplan.getGrade()==2) { // 二级
            LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper<>();
            qw.eq(Teachplan::getParentid, teachplan.getId());
            long count = this.count(qw);
            if (count>0) { // 该二级分类下有三级，不允许删除
                throw new BusinessException(ErrorCode.UPDATEEERROR);
            }
            // 没有三级，直接删除
            this.removeById(id);
        }else{ // 三级
            // 课程章节数量-1
            courseBase.setPlanNum(courseBase.getPlanNum()-1);
            courseBaseService.updateById(courseBase);
            // 直接删
            this.removeById(id);
        }
        // 5.返回成功
        return ResponseResult.okResult();
    }
}
